package com.example.micrometerdemo.service;

import com.example.micrometerdemo.bean.PaymentRequest;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;

public class PaymentService {
    // 手动记录支付耗时（Timer）
    public void processPayment(PaymentRequest request) {
        // 开始计时
        Timer.Sample sample =Timer.start();
        try {
            // 模拟支付处理
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 结束计时并记录指标（带标签）
            sample.stop(Metrics.timer("payment.process.time", "channel", request.getChannel()));
        }
    }

    // 手动记录支付耗时（Timer）
    public void processPayment1(PaymentRequest request) {
        // 开始计时
        Timer.Sample sample =Timer.start();
        Timer timer = Metrics.timer("payment.process.time", "channel", request.getChannel());
        try {
            // 模拟支付处理
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 结束计时并记录指标（带标签）
            sample.stop(timer);
        }
    }

    // 手动记录支付耗时（Timer）
    public void processPayment2(PaymentRequest request) {
        Metrics.timer("payment.process.time", "channel", request.getChannel()).record(() -> {
            try {
                // 模拟支付处理
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

    // 手动统计支付失败次数（Counter）
    public void recordPaymentFailure(String reason) {
        Metrics.counter("payment.failure.count", "reason", reason).increment();
    }
}
